package my.framework.ssm.sample.common.mq.redis;

import lombok.extern.log4j.Log4j2;
import my.framework.ssm.sample.common.enums.NotifyEnum;
import my.framework.ssm.sample.service.NotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * redis消息监听器
 *
 * @author NuKi
 * @date 2018/11/25 13:51
 */
@Log4j2
@Component
public class RedisMqListener implements MessageListener {

    @Autowired
    private NotifyService notifyService;

    /**
     * 订阅接收发布者的消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        long startTime = System.currentTimeMillis();
        Object msg = RedisSerializer.json().deserialize(message.getBody());
        // 缓存消息是序列化的，需要反序列化。然而new String()可以反序列化，但静态方法valueOf()不可以
        log.info("主题【{}】消息【{}】接收成功", RedisSerializer.string().deserialize(pattern));
        notifyService.sendAll(Objects.toString(msg));
        log.info("主题【{}】消息【{}】处理完成: {}s", RedisSerializer.string().deserialize(pattern)
                , RedisSerializer.json().deserialize(message.getBody()), (System.currentTimeMillis() - startTime) / 1000);

    }

    /**
     * 监听主题集合
     *
     * @return
     */
    public static List<Topic> getTopicList() {
        return NotifyEnum.getNotifyTopicList();
    }
}
